package com.zhang.third.day09;

import com.zhang.third.utils.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;

/**
 * @title:
 * @author: zhang
 * @date: 2022/4/13 14:49
 */
public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(
                        new Event("user-1", "fail", 1000L),
                        new Event("user-1", "fail", 2000L),
                        new Event("user-2", "success", 3000L),
                        new Event("user-1", "fail", 4000L),
                        new Event("user-1", "fail", 5000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .keyBy(r -> r.key)
                .process(new KeyedProcessFunction<String, Event, String>() {
                    // hashmap保存状态机
                    // （当前状态，接受的的类型）=> 将要跳转到的状态
                    private HashMap<Tuple2<String, String>, String> stateMachine = new HashMap<>();

                    // 保存当前状态
                    private ValueState<String> currentState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // INITIAL状态接收fail事件，跳转到s1
                        stateMachine.put(Tuple2.of("INITIAL", "fail"), "S1");
                        stateMachine.put(Tuple2.of("S1", "fail"), "S2");
                        stateMachine.put(Tuple2.of("S2", "fail"), "FAIL");
                        stateMachine.put(Tuple2.of("INITIAL", "success"), "SUCCESS");
                        stateMachine.put(Tuple2.of("S1", "success"), "SUCCESS");
                        stateMachine.put(Tuple2.of("S2", "success"), "SUCCESS");

                        currentState = getRuntimeContext().getState(
                                new ValueStateDescriptor<String>(
                                        "current-state",
                                        Types.STRING
                                )
                        );
                    }

                    @Override
                    public void processElement(Event in, KeyedProcessFunction<String, Event, String>.Context ctx, Collector<String> out) throws Exception {
                        if (currentState.value() == null) {
                            currentState.update("INITIAL");
                        }
                        // 查找将要跳转的状态
                        String nextState = stateMachine.get(Tuple2.of(currentState.value(), in.value));
                        if (nextState.equals("FAIL")) {
                            out.collect("用户" + in.key + "连续三次登录失败！！！");
                            currentState.update("S2");
                        } else if (nextState.equals("SUCCESS")) {
                            currentState.update("INITIAL");
                        } else {
                            // 直接跳转下一个状态
                            currentState.update(nextState);
                        }
                    }
                })
                .print();


        env.execute();
    }
}
